<template>
  <div class="about">
    <table>
      <thead>
        <tr>
          <th>id</th>
          <th>名字</th>
          <th>价格</th>
          <th>类型</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in arr" :key="item.id">
          <td>{{ item.id }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.price }}</td>
          <td>{{ item.type }}</td> 
          <td>
            <button @click="handleDelete(item.id)">删除</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import { getCode, shan } from "@/utils/https";
import { onMounted, ref } from "vue";

export default {
  setup() {
    let arr = ref([]);
    const fetchData = () => {
      getCode().then((res) => {
        arr.value = res.data ||[];
      }).catch(err => {
        console.error("获取数据失败:", err);
      });
    };
    
    // 初始化加载数据
    onMounted(() => {
      fetchData();
    });
    
    // 处理删除操作
    const handleDelete = (id) => {
      if (confirm('确定要删除这条数据吗？')) {
        shan(id).then((res) => {
          console.log(res);
          
          console.log('删除结果:', res);
          fetchData()
          if (res.code === 200) { 
            alert('删除成功');
            fetchData(); // 重新加载数据
          } else {
            alert((res.message || '服务器返回错误'));
          }
        }).catch(error => {
          console.error('删除请求失败:', error);
          alert('删除失败，网络错误或服务器无响应');
        });
      }
    };
    
    return { 
      arr,
      handleDelete
    };
  },
};
</script>
<style lang='less' scoped>
/* 样式保持不变 */
table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
}

th, td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: left;
}

th {
  background-color: #f5f5f5;
  font-weight: bold;
}

tr:nth-child(even) {
  background-color: #f9f9f9;
}

button {
  background-color: #ff4d4f;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #d9363e;
}
</style>